# Title     : TODO
# Objective : TODO
# Created by: Administrator
# Created on: 2019/6/18

createWhenNoExist <- function(f) {
  !dir.exists(f) && dir.create(f)
}

library(gplots)
library(Hmisc)
library(optparse)
library(ropls)
library(magrittr)
library(ComplexHeatmap)
library(tools)
library(circlize)
library(tidyverse)

option_list <- list(
  make_option("--i", default = "AllMet.csv", type = "character", help = "metabolite data file"),
  make_option("--g", default = "SampleInfo.csv", type = "character", help = "sample group file"),
  make_option("--et", default = "", type = "character", help = "extra data dir")
)
opt <- parse_args(OptionParser(option_list = option_list))

sampleInfo <- read.csv(opt$g, header = T, stringsAsFactors = F) %>%
  select(c("SampleID", "ClassNote"))
classNotes <- sampleInfo %>%
  .$ClassNote %>%
  unique()
groupNames <- c(classNotes, paste0(classNotes, collapse = "_vs_"))

for (groupName in groupNames) {
  parent <- str_replace_all(groupName, "_vs_", "_and_")
  createWhenNoExist(parent)
  files <- list.files(opt$et, full.names = T)
  for (file in files) {
    dirName <- basename(file) %>%
      file_path_sans_ext()
    finalParent <- paste0(parent, "/", dirName)
    if (!dir.exists(finalParent)) {
      next
    }

    corFile <- str_c(finalParent, "/Inter_r_Matrix.csv")

    corData <- read_csv(corFile)
    print(corData)

    pData <- read_csv(str_c(finalParent, "/Inter_P_Matrix.csv")) %>%
      column_to_rownames("X1") %>%
      as.matrix()

    fileName <- paste0(finalParent, "/Inter_Correlation_Heatmap.pdf")

    colors <- rev(colorRampPalette(RColorBrewer::brewer.pal(10, "RdBu"))(256))

    plotData <- corData %>%
      column_to_rownames("X1") %>%
      as.matrix()

    rowNum <- nrow(plotData)
    colNum <- ncol(plotData)

    row_names = rownames(plotData)
    col_names = colnames(plotData)
    max_row_chr_num = max(nchar(row_names))
    max_col_chr_num = max(nchar(col_names))

    height <- max(2 + (rowNum - 10) * 0.1, 2) + 1 / 4 * max_col_chr_num
    height
    width <- max(2 + (colNum - 10) * 0.1, 2) + 1 / 4 * max_row_chr_num
    width

    maxLength <- max(c(height, width))

    pdf(fileName, width = maxLength, height = maxLength)

    eachHeight <- 1 / rowNum

    htList <- Heatmap(plotData, col = colors, show_column_names = T, cluster_rows = T, cluster_columns = T,
                      name = "", row_names_gp = gpar(fontsize = 6, fontfamily = "Times"), show_row_names = T, show_heatmap_legend = F,
                      column_names_gp = gpar(fontsize = 6, fontfamily = "Times"), cell_fun = function(j, i, x, y, width, height, fill) {
        value <- pData[i, j]
        str <- if (value < 0.01) {
          "+"
        }else if (value < 0.05) {
          "*"
        }else ""
        top <- if (str == "*") {
          y - unit(eachHeight * 0.12, "npc")
        }else y
        grid.text(str, x, top, gp = gpar(fontsize = 9), hjust = 0.5, vjust = 0.5, just = "center")
      })

    rLgd <- Legend(col_fun = colorRamp2(seq(-1, 1, length.out = 256), colors), at = seq(-1, 1, 0.5), title = "",
                   title_gp = gpar(fontsize = 12, fontfamily = "Times"), grid_height = unit(7.5, "mm"),
                   labels_gp = gpar(fontsize = 12, fontfamily = "Times"))

    pLegend <- Legend(pch = c("+", "*"), type = "points", labels = c("p<0.01", "0.01<=p<0.05"), title = "",
                      labels_gp = gpar(fontsize = 9, fontfamily = "Times"), title_gp = gpar(fontsize = 12, fontfamily = "Times"),
                      ncol = 1, grid_height = unit(5, "mm"),
    )
    pd <- packLegend(list = list(rLgd, pLegend), row_gap = unit(0.5, "cm"))

    draw(htList, heatmap_legend_side = "right", annotation_legend_side = "right",
         padding = unit(c(0.5, 0.5, 0.5, 0.5), "cm"), annotation_legend_list = pd
    )
    dev.off()
  }
}





